# E:\Download\ChatRoomProject\Document\main.py
import asyncio

from fastapi import FastAPI
import nacos
from starlette.middleware.cors import CORSMiddleware
import aioredis
import yaml

import database
from route import chatV2, upload
from service import question_service, resumes_service

app = FastAPI()

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# NACOS 客户端
nacos_client = nacos.NacosClient("localhost:8850", namespace="public")

# 从NACOS获取配置
config = nacos_client.get_config("document.yaml", "document")
db_config = yaml.safe_load(config)

# 👇 在这里初始化数据库模块
from database import init_database,create_tables
init_database(db_config)
create_tables()

# 初始化 Redis
redis_config = db_config.get('redis', {})

# 在 startup 函数中添加心跳任务
async def send_heartbeat():
    while True:
        try:
            nacos_client.send_heartbeat("DOCUMENT", "localhost", 8085)
            await asyncio.sleep(5)  # 每5秒发送一次心跳
        except Exception as e:
            print(f"Heartbeat failed: {e}")
            await asyncio.sleep(5)

async def startup():
    """服务启动时注册到 Nacos"""
    nacos_client.add_naming_instance("DOCUMENT", "localhost", 8085)
    asyncio.create_task(send_heartbeat())  # 启动心跳协程

    redis_client = aioredis.Redis(
        host=redis_config.get('host', 'localhost'),
        port=redis_config.get('port', 6379),
        password=redis_config.get('password'),
        db=redis_config.get('db', 0),
        decode_responses=True
    )
    chatV2.init_redis(redis_client)
    question_service.init_redis(redis_client)  # 直接传递给 question_service
    resumes_service.init_redis(redis_client)

app.add_event_handler("startup", startup)

# 注册路由
upload.init_config(db_config)
chatV2.init_config(db_config)

app.include_router(upload.router, prefix="/upload")
app.include_router(chatV2.router, prefix="")

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8085)
